package cn.yd.rb.controller;

import cn.yd.rb.exception.CustomException;
import cn.yd.rb.po.*;
import cn.yd.rb.service.ChapterService;
import cn.yd.rb.service.NewsService;
import cn.yd.rb.service.NovelService;
import com.github.pagehelper.PageHelper;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.jasper.tagplugins.jstl.core.ForEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
@Controller
@RequestMapping("/novel")
public class NovelController {

    @Autowired
    private NovelService novelService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private ChapterService chapterService;

    @RequestMapping(value="/findNovel")
    public String findNovel(HttpServletRequest request,@RequestParam(value="pc",required=true,defaultValue="1") Integer pc, NovelQueryVo novelQueryVo){

        //定义每页显示的商品数量
        Integer ps = 10;

        //查询数据表获取所有商品信息
        try {
            PageBean<Novel> pageBean = novelService.findNovelAll(pc,ps,novelQueryVo);
            request.setAttribute("pageBean", pageBean);

            List<Type> noveltypeList = novelService.findNoveltype();
            request.setAttribute("noveltypeList", noveltypeList);

        } catch (Exception e) {
            new RuntimeException();
        }

        return "novelSearch";
    }
    //小说查询
    @RequestMapping(value="/novelSearch")
    public String novelSearch(Model model, HttpSession session, Integer id) throws Exception{

        //获取分类列表
        List<Type> noveltypeList = novelService.findNoveltype();
        model.addAttribute("noveltypeList",noveltypeList);

        //根据id查询进入详情页
        Novel novel= novelService.findNovelById(id);
        model.addAttribute("novel",novel);
        //session存储当前novel
        session.setAttribute("novelSession", novel);

        model.addAttribute("id",id);
        return "detail";
    }
    //图片上传---测试
    @RequestMapping(value="/testUpload")
    public String testUpload(Novel novel, HttpServletRequest request, MultipartFile file) throws Exception{

        List<String> tlist = new ArrayList<>();
        /**
         * 储存章节
         */
        List<String> llist =new ArrayList<>();

        /*try {
            File file1 = new File("http://106.53.67.228//group1//M00//00//01//rBAABl1foO-ALMSwAABo1qZyzdk577.txt");
            if(file1.isFile() && file1.exists()) {
                InputStreamReader isr = new InputStreamReader(new FileInputStream(file1), "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String lineTxt = null;
                while ((lineTxt = br.readLine()) != null) {
                    System.out.println(lineTxt);
                }
                br.close();
            } else {
                System.out.println("文件不存在!");
            }
        } catch (Exception e) {
            System.out.println("文件读取错误!");
        }*/
        FastDFSClient client =new FastDFSClient("D:\\client.conf");
        String chapterpath=client.uploadFile(file.getBytes(),"txt");
        System.out.println(chapterpath);
        String read="";
        String body="";
         String readStr ="";
        try{
             URL url =new URL("http://106.53.67.228//"+chapterpath);
             HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();
             urlCon.setConnectTimeout(5000);
             urlCon.setReadTimeout(5000);
             BufferedReader br =new BufferedReader(new InputStreamReader( urlCon.getInputStream()));
            Integer index=1;
             while ((read = br.readLine()) !=null) {
                 if((read.contains("第"))&&(read.contains("章"))){
                     index++;
                     tlist.add(read);
                     if(index==2){
                         body=body+read.concat("<br/>");
                     }
                     if(index>2){
                         llist.add(body); body="";
                         body=body+read.concat("<br/>");

                     }


                 }
                 else{
                     body=body+read.concat("<br/>");
                 }

                 readStr = readStr + read;
             }
            llist.add(body);
            /*FastDFSClient client =new FastDFSClient("D:\\client.conf");
            String chapterpath=client.uploadFile(file.getBytes(),"txt");*/
          /*  chapter.setChapterurl(chapterpath);
            chapter.setNovelId(id1);
            chapterService.addChapter(chapter);*/
             br.close();
            for(int i=0;i<tlist.size();i++) {
                System.out.println(tlist.get(i));
                System.out.println();}

            for(int i=0;i<llist.size();i++) {
                System.out.println(llist.get(i));
                System.out.println();
            }
            System.out.println(tlist.size());
            System.out.println(llist.size());
        }
         catch (IOException e) {
            // TODO Auto-generated catch block
             readStr ="f";
        }
        System.out.println(readStr);
        return "redirect:addNovel.jsp";//返回商品列表方法--重定向
    }
    //新闻查询
    @RequestMapping(value="/findNews")
    public String newsSearch(Model model, Integer id) throws Exception {
        List<Type> noveltypeList = novelService.findNoveltype();
        model.addAttribute("noveltypeList",noveltypeList);
        News newsRes =newsService.findNewsById(id);
        model.addAttribute("newsRes",newsRes);
        return "news";
    }
    //目录分类
    @RequestMapping(value="/novelCatlogue")
    public String novelCatlogue(Model model,HttpSession session) throws Exception {
        Novel  novelSession = (Novel)session.getAttribute("novelSession");
        model.addAttribute("novel",novelSession);
        //获取分类列表
        List<Type> noveltypeList = novelService.findNoveltype();
        model.addAttribute("noveltypeList",noveltypeList);
        //获取章节列表
        List<Chapter> chapterList= novelService.findChapterAllById(novelSession.getId());
        model.addAttribute("chapterList",chapterList);
        List<Novel> novelList= novelService.findNovelAll(novelSession.getTypeId());
        model.addAttribute("novelList",novelList);
        return "catlogue";
    }
    //增加下载次数
    @RequestMapping("/addCounts")
    public void addCounts(HttpSession session){
        Novel  novelSession = (Novel)session.getAttribute("novelSession");
        novelService.addCounts(novelSession.getId());
    }

    @RequestMapping("/read/{id}")
    public String read(HttpServletRequest request,Model model, @PathVariable("id")Integer id,@RequestParam(value = "pc",required = true,defaultValue = "1")Integer pc,ChapterQueryVo chapterQueryVo){
        Integer pageSiez=1;

        HttpSession session=request.getSession();
        session.setAttribute("novelid",id);

        PageBean<Chapter> pageBean=chapterService.findAllChapterForNovel(0,session,pc,pageSiez,chapterQueryVo,id);

        model.addAttribute("pageBean",pageBean);

        List<Type> noveltypeList = novelService.findNoveltype();
        model.addAttribute("noveltypeList",noveltypeList);

        return "read";
    }
}
